﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;

namespace System
{
    public partial class ContainerManager
    {
        public static readonly ContainerManager Current = new ContainerManager();
        private IContainer _container;
        public IContainer Container
        {
            get
            {
                if (_container == null)
                {
                    //var builder = new ContainerBuilder();
                    //_container = builder.Build();
                }
                return _container;
            }
        }
        protected ContainerManager()
        {

        }
        /// <summary>
        /// 配置注册
        /// </summary>
        public virtual void Configure()
        {
            Action<ContainerBuilder> action = x =>
                {
                    var dependencyRegistrars = AppDomain.CurrentDomain
                                                        .GetInstancesOfTypesImplementing<IDependencyRegistrar>()
                                                        .OrderBy(t => t.Order);
                    dependencyRegistrars.ForEach(dependencyRegistrar => dependencyRegistrar.Register(x));
                }; 
            var builder = new ContainerBuilder();
            action.Invoke(builder);
            _container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(_container);

        }
    }
}
